package cn.lbwfree.web.controller;

import cn.lbwfree.web.entity.Admin;
import cn.lbwfree.web.entity.Book;
import cn.lbwfree.web.entity.Reader;
import cn.lbwfree.web.service.BookService;
import cn.lbwfree.web.service.LoginService;
import cn.lbwfree.web.service.impl.BookServiceImpl;
import cn.lbwfree.web.service.impl.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private LoginService loginService = new LoginServiceImpl();
    private BookService bookService =new BookServiceImpl();
    /**
     * 登陆业务
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String type = request.getParameter("type");
        Object object = loginService.login(username, password, type);
        if (object != null){
            HttpSession session = request.getSession();
            switch (type){
                case "reader":
                    Reader reader = (Reader)object;
                    session.setAttribute("reader", reader);
                    System.out.println("success");
                    //跳转书栏
                    response.sendRedirect("/book?page=1");
//                    List<Book> list =new ArrayList<Book>();
//                    list=bookService.findAll();
//                    request.setAttribute("list", list);
//                    request.getRequestDispatcher("index.jsp").forward(request,response);
                    break;
                case "admin":
                    Admin admin = (Admin)object;
                    session.setAttribute("admin",admin);
                    System.out.println("success");
                    //跳转管理页面
                    response.sendRedirect("/admin?method=findAllBorrow&page=1");
                    break;
            }

        }else {
            response.sendRedirect("login.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
